package cn.z2huo.algorithm.sort.data;

import cn.hutool.core.text.csv.CsvWriteConfig;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

/**
 * <p>排序使用的数组 csv 生成类
 *
 * @author z2huo
 */
class CsvTestDataGenerator {

    private static final String TEST_DATA_PATH = "algorithm/src/test/resources/csv/sort/";

    /**
     * <p>十万条和一百万条测试数据文件需要生成，没有提交到 git
     */
    private static final int TEST_DATA_SIZE = 1_000;
//    private static final int TEST_DATA_SIZE = 10_000;
//    private static final int TEST_DATA_SIZE = 100_000;
//    private static final int TEST_DATA_SIZE = 1_000_000;

    private static final int ARRAY_MIN_LENGTH = 10;

    private static final int ARRAY_MAX_LENGTH = 100;

    private static final int MAX_VALUE = 10000;

    public static void main(String[] args) throws FileNotFoundException {

        File file = ResourceUtils.getFile(TEST_DATA_PATH + "test_data_" + TEST_DATA_SIZE + ".csv");

        CsvWriteConfig csvWriteConfig = CsvWriteConfig.defaultConfig();

        try (FileWriter fileWriter = new FileWriter(file);
             CsvWriter csvWriter = new CsvWriter(fileWriter, csvWriteConfig)) {

            for (int i = 0; i < TEST_DATA_SIZE; i++) {
                int[] array = generateArray();
                int[] resultArray = sortArray(array);

                csvWriter.writeLine(StringUtils.join(array, ';'), StringUtils.join(resultArray, ';'));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>随机生成数组，长度随机，数组中各个位置数据随机
     * @return  数组
     */
    private static int[] generateArray() {
        int arrayLength = RandomUtil.randomInt(ARRAY_MIN_LENGTH, ARRAY_MAX_LENGTH + 1);
        int[] array = new int[arrayLength];
        for (int i = 0; i < array.length; i++) {
            array[i] = RandomUtil.randomInt(0, MAX_VALUE);
        }
        return array;
    }

    /**
     * 数组排序
     * @param array 数组
     * @return  排序后的新数组
     */
    private static int[] sortArray(int[] array) {
        int[] newArray = Arrays.copyOf(array, array.length);
        Arrays.sort(newArray);
        return newArray;
    }

}
